package org.farm2.service.impl;

import org.farm2.auth.domain.Post;
import org.farm2.auth.dto.MenusDto;
import org.farm2.auth.service.ActionsServiceInter;
import org.farm2.auth.service.PostServiceInter;
import org.farm2.base.domain.FarmUserContext;
import org.farm2.luser.domain.LocalOrg;
import org.farm2.luser.domain.LocalUser;
import org.farm2.luser.service.LocalOrgServiceInter;
import org.farm2.luser.service.LocalUserServiceInter;
import org.farm2.service.inter.FarmUserServiceInter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 用戶信息读取的实现类，将来可以替换为第三方实现
 */
@Component
public class FarmUserService implements FarmUserServiceInter {
    @Autowired
    private LocalUserServiceInter localUserServiceImpl;
    @Autowired
    private LocalOrgServiceInter localOrgServiceImpl;
    @Autowired
    private PostServiceInter postServiceImpl;
    @Autowired
    private ActionsServiceInter actionsServiceImpl;
    @Override
    public FarmUserContext getUserByLoginName(String loginname) {
        LocalUser localuser = localUserServiceImpl.getLocalUserByLoginName(loginname);
        if (localuser == null) {
            return null;
        }
        FarmUserContext userContext = new FarmUserContext();
        userContext.setLoginname(localuser.getLoginname());
        userContext.setState(localuser.getState());
        userContext.setType(localuser.getType());
        userContext.setName(localuser.getName());
        userContext.setPassword(localuser.getPassword());
        LocalOrg org = localOrgServiceImpl.getLocalOrgById(localuser.getOrgid());
        if (org != null) {
            userContext.getTags().add(org.getName());
        }
        List<String> postids = postServiceImpl.getUserPost(localuser.getLoginname());
        for (String id : postids) {
            Post post = postServiceImpl.getPostById(id);
            if (post != null) {
                userContext.getTags().add(post.getName());
            }
        }
        return userContext;
    }

    @Override
    public List<MenusDto> getUserMenus(FarmUserContext user, String domain) {
        List<MenusDto> menus = null;
        if (user.getType().equals("3")) {
            menus = actionsServiceImpl.getAllMenus(domain);
        } else {
            menus = actionsServiceImpl.getMenusByUserKey(user.getLoginname(), domain);
        }
        return menus;
    }
}
